package com.tanhua.admin.listener;

import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *  @title RedisKeyExListener
 *  修改redis 的配置文件 notify-keyspace-events （""）Ex
 *  监听redis中已经过期的key
 */
@Component
@Slf4j
public class RedisKeyExListener extends KeyExpirationEventMessageListener {
    @DubboReference
    private UserInfoApi userInfoApi;

    public RedisKeyExListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        if (expiredKey.startsWith(Constants.FreezeLogin_KEY)||expiredKey.startsWith(Constants.FreezeComment_KEY)||expiredKey.startsWith(Constants.FreezeMovement_KEY)){
            log.info("过期的key是: "+expiredKey);
            String[] split = expiredKey.split("_");
            String uid = split[1];
            Long userId = Long.valueOf(uid);
            //解除禁止登录状态
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setUserStatus("1");
            userInfo.setUpdated(new Date());
            userInfoApi.update(userInfo);
            log.info("已解除"+uid+"冻结状态");
        }
    }
}